package com.wx.JerseySpring.action;

import com.wx.JerseySpring.entity.ResultParam;
import com.wx.JerseySpring.entity.User;
import com.wx.JerseySpring.service.UserService;
import com.wx.JerseySpring.util.Context;
import com.wx.JerseySpring.util.JerseySpringUtil;
import com.wx.JerseySpring.util.ResultUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;

/**
 * Created by Administrator on 2016/11/16.
 */
@Component
@Path("/user")
@Scope("prototype")
@Produces({"application/json"})
public class UserAction {
    Logger log = Logger.getLogger(UserAction.class);
    @Resource
    private UserService userService;

    @GET
    @Path("/list")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String getAllUser( @QueryParam("jsonpcallback") String jsonpcallback){
        List<User> users = userService.getAllUser();
//        for(User u:users){
//            result.append(u.toString()+"/n");
//        }
        String result = jsonpcallback+"("+ ResultUtil.resultStr(1,true,users.get(0))+")";
        return result;
    }

    @GET
    @Path("/login/{userName}/{pwd}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String userLogin(@PathParam("userName")String userName,
                            @PathParam("pwd")String pwd,
                            @QueryParam("jsonpcallback") String jsonpcallback){
        HttpServletRequest request = JerseySpringUtil.getRequest();
        ResultParam resultParam = new ResultParam();
        resultParam.setCode(1);
        resultParam.setFlog(true);
        String result = "";
        User user = new User();
        user.setName(userName);
        user.setPassword(pwd);
        User user1 = (User) request.getSession().getAttribute(Context.USER_CONTEXT);
        if(user1 !=null){
            result = jsonpcallback+"("+ ResultUtil.resultStr(1,true,user1)+")";
            log.info(result);
            return result;
        }
        request.getSession().setAttribute(Context.USER_CONTEXT,user);
        result = jsonpcallback+"("+ResultUtil.resultStr(1,true,user)+")";
        log.info(result);
        return result;
    }
}
